<template>
    <div>
        <!-- 面包屑导航 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
       <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
       <el-breadcrumb-item>商品管理</el-breadcrumb-item>
       <el-breadcrumb-item>参数列表</el-breadcrumb-item>
       </el-breadcrumb>

       <!-- card视图 -->
        <el-card>
            <!-- 添加按钮 -->
            <el-row>
                <el-col>
                     <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable='false' show-icon></el-alert> 
                </el-col>
            </el-row>


            <!-- 级联选择器 -->
                 <!-- options：用来指定数据源 -->
                 <!-- props：用来指定配置对象 -->
            <span>选择商品分类：</span>
            <el-cascader expandTrigger = 'hover' v-model="paramsCaacaderModel" :options="paramsList" :props="casCaderProps" 
            @change="handleParamsChange" clearable>
            </el-cascader>
    
    
  
            <!-- tabs标签页 -->
            <el-tabs v-model="tabsActive" @tab-click="handleTabsClick">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="isBtnCalculate" @click="addDialogVisible=true">添加参数</el-button>
                     <!-- 渲染动态框的数据 -->
                    <el-table :data='manyTableData' style="width: 100%" stripe border>
                        <el-table-column  type="expand">
                            <!-- tag标签 -->
                            <template slot-scope="scope">
                                <el-tag  v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close='tagDeletePop(i,scope.row)'>{{item}}</el-tag>
                                <!-- tag添加输入框 -->
                                <el-input  class="input-new-tag"  v-if="scope.row.inputVisible"  v-model="scope.row.inputValue"  ref="saveTagInput" size="small"
                                  @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- tag添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#"  type="index"></el-table-column>
                        <el-table-column label='参数名称' prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" class="el-icon-edit" size="small" @click="editBtnPop(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" class="el-icon-delete" size="small" @click="editDeletePop(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>  
            </el-tab-pane>               
            <el-tab-pane label="静态参数" name="only">
                <el-button type="primary" :disabled="isBtnCalculate" @click="addDialogVisible=true">添加参数</el-button>
                 <!-- 渲染静态框的数据 -->
                    <el-table :data='onlyTableData' style="width: 100%" stripe border>
                        <el-table-column  type="expand">
                            <template slot-scope="scope">
                                <el-tag  v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close='tagDeletePop(i,scope.row)'>{{item}}</el-tag>
                                <!-- tag添加输入框 -->
                                <el-input  class="input-new-tag"  v-if="scope.row.inputVisible"  v-model="scope.row.inputValue"  ref="saveTagInput" size="small"
                                  @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- tag添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#"  type="index"></el-table-column>
                        <el-table-column label='属性名称' prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" class="el-icon-edit" size="small" @click="editBtnPop(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" class="el-icon-delete" size="small" @click="editDeletePop(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>             
                </el-tab-pane>
            </el-tabs>


            <!-- tabs 添加按钮 弹框 -->
            <el-dialog  :title="'添加'+ titleText" :visible.sync="addDialogVisible" width="50%" @close='addClosePop'>
                <el-form :model="addForm" :rules="addFormRules" ref="ruleFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addSubmitPop">确 定</el-button>
                </span>
            </el-dialog>


            <!-- 编辑弹框 弹框 -->
            <el-dialog  :title="'编辑'+ titleText" :visible.sync="editDialogVisible" width="50%" @close='editClosePop'>
                <el-form :model="editForm" :rules="editFormRules" ref="editruleFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editSubmitPop">确 定</el-button>
                </span>
            </el-dialog>
 
   
  


           





        </el-card>
    </div>
</template>

<script>
import { log } from 'util'
export default {
    data() {
        return{


            //  所有分类参数数据
            paramsList:[],

            //  指定级联配置对象
            casCaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },

            //  级联选择框双向绑定到的数组
            paramsCaacaderModel:[],

            //  tabs标签页双向绑定
            tabsActive:'many',

            //   动态参数的属性
            manyTableData:[],
            //   静态参数的属性
            onlyTableData:[],

            // 控制添加对话框的显示与隐藏
            addDialogVisible:false,

            // 验证添加弹框
            addForm:{
                attr_name:""
            },
            addFormRules:{
                attr_name:[
                    { required: true, message: '请输入内容', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ]
            },

            // 编辑弹框
            editDialogVisible:false,
            editForm:{
                attr_name:'',
                attr_id:''
            },
            editFormRules:{
                 attr_name:[
                    { required: true, message: '请输入内容', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ]
            },

            // tag添加




        }
    },


    // 生命周期
    created(){
        this.getparamsList()
    },


    // 方法事件
    methods:{

        //  获取分类参数列表
        async getparamsList(){
           const {data:res} = await this.$http.get('categories')
           if(res.meta.status !== 200) {
               return this.$message.error('获取分类参数失败')
           }
           this.paramsList = res.data          
        },


        //  级联选择框中项变化 触发事件
        handleParamsChange(){
            this.getParamsData()
            this.manyTableData = ''
            this.onlyTableData = ''

        },


        //  tabs 页签点击事件的处理函数
        handleTabsClick(){
            if ( !this.cataId)  return  this.$message.error('请选择三级分类') 
            this.getParamsData()
        },


        //   获取参数的列表数据
        async getParamsData(){
           const { data:res } = await this.$http.get(`categories/${this.cataId - 0}/attributes`,{params:{sel: this.tabsActive}})
           if(res.meta.status !== 200 ){
               return this.$message.error('获取参数列表失败！')                 
           }
           res.data.forEach(item => {
              item.attr_vals =  item.attr_vals ? item.attr_vals.split(',') : [],        
              item.inputVisible = false,
              item.inputValue = ''
           })                   
           if(this.tabsActive ==='many') {
               this.manyTableData = res.data
           }else{
               this.onlyTableData = res.data
           }
           
        },


        //   清空添加框事件
        addClosePop(){
            this.$refs.ruleFormRef.resetFields()
        },


        // 添加按钮确定事件
        addSubmitPop(){
              this.$refs.ruleFormRef.validate( async valid => {
                  if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cataId -0}/attributes`,{
                attr_name:this.addForm.attr_name,
                attr_sel:this.tabsActive
            })
            if(res.meta.status !==201) {            
                return this.$message.error('添加参数列表失败！')
            }
            this.$message.success('添加参数列表成功')
            this.getParamsData()
            this.addDialogVisible = false
              })
        },


        //  清空编辑按钮确定事件
        editClosePop(){
            this.$refs.editruleFormRef.resetFields()
        },


        //   点击编辑按钮查询事件
        async editBtnPop(attr_id){
            const {data:res} = await this.$http.get(`categories/${this.cataId}/attributes/${attr_id}`,{params:{
                attr_sel:this.tabsActive
            }})
            if(res.meta.status !== 200) {
                return this.$message.error('获取编辑参数失败！')
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },


        //   编辑按钮确定事件
        editSubmitPop(attr_id){
            this.$refs.editruleFormRef.validate( async valid =>{
                const {data:res} = await this.$http.put(`categories/${this.cataId}/attributes/${this.editForm.attr_id}`,{
                attr_name:this.editForm.attr_name,
                attr_sel:this.tabsActive
            })
                if(res.meta.status !== 200){
                    return this.$message.error('更改编辑失败！')
                }
                this.$message.success('更改编辑成功！')
                this.getParamsData()
                this.editDialogVisible = false              
            })      
        },


        //   删除按钮事件
        async editDeletePop(attr_id){
            const  deleteData = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
             cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)   
            if(deleteData !== 'confirm') return
            const {data:res} = await this.$http.delete(`categories/${this.cataId}/attributes/${attr_id}`)
            if(res.meta.status !==200){         
                return this.$message.error('删除失败！')
            }
            this.$message.success('删除成功！')
             this.getParamsData()
        },


        // tag input框添加事件
        async handleInputConfirm(row){
            if(row.inputValue.trim().length ===0 ){
                row.inputVisible = false
                row.inputValue = ''
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            this.saveAttrVals(row)

        },


        //  将对 attr_vals的操作保存到数据库
        async saveAttrVals(row){
            const {data:res} = await this.$http.put(`categories/${this.cataId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join()
            })
            if(res.meta.status !==200){
                this.$message.error('修改参数失败！')
            }
            this.$message.success('修改参数成功！')
        },


        // tag 按钮添加事件
        showInput(row){
            row.inputVisible = true
            //  让文本框自动获得焦点
            //  $nexTick 方法的作用，就是当页面上元素被重新渲染后，才会指定回调函数中的代码
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus()
        })
        },


        // tag删除事件
        async tagDeletePop(i,row){
          row.attr_vals.splice(i,1)
          this.saveAttrVals(row)

           
        }









    },

    // 计算属性
    computed:{
        //  tabs 如果按钮需要被禁用，则返回true ， 否则返回false
        isBtnCalculate(){
            if(this.paramsCaacaderModel.length !==3) {              
                return true
            }
                return false
        }, 


        //  当前选中的三级分类ID
        cataId(){
            if(this.paramsCaacaderModel.length === 3 ){ 
                return this.paramsCaacaderModel[2]
            }

            return null
        },



        //  tabs 动态计算标题的文本
        titleText(){
            if(this.tabsActive === 'many') {
                return '动态属性'
            }
                return '静态属性'
        }






    }
}
</script>

<style lang="less" scoped>
.el-alert {
    margin-bottom: 15px;
}
.el-table {
    margin-top: 15px;
}
.el-tag {
    margin:0 15px 0 0 ;
}
.el-input {
    width: 130px;
}
</style>